package com.amethyst.swagger3.demo.config;

import com.amethyst.swagger3.demo.common.ResponseResult;
import com.amethyst.swagger3.demo.common.exception.BizException;
import com.amethyst.swagger3.demo.enums.CodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.lang.reflect.UndeclaredThrowableException;

/**
 * @author Amethyst
 * @date 2021/10/14
 */
@RestControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandleConfig {

    @ExceptionHandler(Exception.class)
    public Object handlerException(Exception e) {
        log.error(e.getMessage(), e.getCause());
        if (e instanceof UndeclaredThrowableException) {
            e = (Exception) ((UndeclaredThrowableException) e).getUndeclaredThrowable();
        }
        return ResponseResult.error(CodeEnum.SYSTEM_ERROR);
    }

    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public Object bizExceptionHandler(BizException e){
        log.error(e.getMessage(), e.getCause());
        return ResponseResult.error(e.getErrorCode(), e.getErrorMsg());
    }

}
